public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            // 指向空节点则无环
            if (fast == null || fast.next == null) {
                return false;
            }

            // fast 和 slow 异速前进
            fast = fast.next.next;
            slow = slow.next;

            // 相遇
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    // ListNode 类定义
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        // 测试用例 1：有环
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node2; // 形成环

        boolean hasCycle1 = solution.hasCycle(node1);
        System.out.println("Has Cycle (Test 1): " + hasCycle1); // 输出：Has Cycle (Test 1): true

    }
}
